import PropTypes from '@zh/common-utils/prop-types'
import clone from 'clone'

export default {
  props: {
    pages: PropTypes.array.def([])
  },
  data () {
    return {
      activeKey: ''
    }
  },
  watch: {
    $route: {
      immediate: true,
      handler () {
        this.$route.meta.aliveKey = this.getAliveKey()
        let page = this.pages.find(page => page.meta.aliveKey == this.getAliveKey())
        if (!page) {
          if (this.$route.matched.length > 1) {
            page = this.createPage()
            this.handleRouteChange(page)
          }
        }
        this.$store.updateKeepAlive(this.pages)
        this.activeKey = page.meta.aliveKey
      }
    }
  },
  created () {
    if (this.$route.matched.length > 1) {
      const page = this.createPage()
      this.handleRouteChange(page)
    }
  },
  mounted () {
    // 重写原生方法 history.go
    window.history.back = () => {
      this.go(-1)
    }
    window.history.go = (n) => {
      this.go(n)
    }
    // 重写原生方法 router.replace 方法
    this.$router.history.replace = (location, onResolve, onReject) => {
      this.activeKey && this.remove(this.activeKey)
      // eslint-disable-next-line no-proto
      this.$router.history.__proto__.replace.call(this.$router.history, location, onResolve, onReject)
    }
  },
  beforeDestroy () {
    delete window.history.go
    delete window.history.back
    delete this.$router.replace
  },
  methods: {
    handleRouteChange () { },
    // 返回按钮
    go (n) {
      if (n >= 0 || !parent) {
        window.history.prototype.go(n)
        return
      }
      if (this.pages.length == 1) {
        // 当前只有一个标签，并且当前路由为功能菜单路由，则返回到父级路由
        const page = this.pages[0]
        if (page.meta.type == 3 && page._parent) {
          // 直接关闭当前页
          this.remove(this.activeKey)
          this.$router.push({
            path: page._parent.path,
            query: page._parent.query,
            params: page._parent.params
          })
        }
        return
      }
      // 直接关闭当前页
      this.remove(this.activeKey)
    },
    createPage () {
      const page = {
        path: this.$route.path,
        fullPath: this.$route.fullPath,
        query: this.$route.query,
        params: this.$route.params,
        meta: { ...this.$route.meta || {} }
      }
      delete page.meta._parent
      if (this.$route.meta._parent) {
        page._parent = {
          path: this.$route.meta._parent.path,
          fullPath: this.$route.meta._parent.fullPath,
          query: this.$route.meta._parent.query,
          params: this.$route.meta._parent.params,
          meta: { ...this.$route.meta._parent.meta || {} }
        }
        delete page._parent.meta._parent
      }
      return page
    },
    getAliveKey () {
      let aliveKey = this.$route.fullPath,
        timestampIndex = aliveKey.indexOf('timestamp')
      if (timestampIndex != -1) {
        aliveKey = aliveKey.replace(aliveKey.substring(timestampIndex, timestampIndex + 23), '')
      }
      return aliveKey
    },
    handleRouterViewTitle(title, subtitle) {
      const page = this.pages.find(p => p.meta.aliveKey == this.activeKey)
      if (page) {
        this.$set(page.meta, '_title', subtitle ? `${title} - ${subtitle}` : title)
      }
    },
    onTabChange () {
      const page = this.pages.find(p => p.meta.aliveKey == this.activeKey)
      this.loadRoute(page)
      this.$emit('tabChange', this.activeKey, page)
    },
    loadRoute (page) {
      this.$router.push(page)
    },
    refresh (page) {
      this.$router.reload()
    },
    onEdit (key, action) {
      this[action](key)
    },
    remove (key) {
      const index = this.pages.findIndex(page => page.meta.aliveKey == key)
      let nextOpenPage = null
      if (index == 0) {
        nextOpenPage = this.pages[index + 1]
      } else {
        nextOpenPage = this.pages[index - 1]
      }
      this.pages.splice(index, 1)
      if (!nextOpenPage) {
        return
      }
      // this.$store.updateKeepAlive(this.pages)
      this.loadRoute(nextOpenPage)
      this.$emit('tabChange', this.activeKey, nextOpenPage)
    },
    closeOther (page, index) {
      this.pages.length = 0
      this.pages.push(page)
      // this.$store.updateKeepAlive(this.pages)
      if (this.activeKey !== page.meta.aliveKey) {
        this.loadRoute(page)
        this.$emit('tabChange', this.activeKey, page)
      }
    },
    closeRight (page, index) {
      this.pages.splice(index + 1, this.pages.length - index)
      const currentOpenPage = this.pages.find(page => page.meta.aliveKey == this.activeKey)
      if (currentOpenPage) {
        return
      }
      // this.$store.updateKeepAlive(this.pages)
      this.loadRoute(page)
    },
    closeLeft (page, index) {
      this.pages.splice(0, index)
      const currentOpenPage = this.pages.find(page => page.meta.aliveKey == this.activeKey)
      if (currentOpenPage) {
        return
      }
      // this.$store.updateKeepAlive(this.pages)
      this.loadRoute(page)
    },
    getTabTitle (page) {
      if (page.meta._title) {
        return page.meta._title
      }
      let title = page.meta?.title
      // 功能菜单查找父级节点名称
      if (page.meta.type == 3 && page._parent?.meta?.title) {
        title = `${page._parent?.meta?.title}-${title}`
      }
      return title
    }
  }
}